package com.club.football.controller;


import com.club.football.common.BusinessException;
import com.club.football.common.UserHolder;
import com.club.football.entity.User;
import com.club.football.service.FilesService;
import com.club.football.service.UserService;
import com.club.football.utils.FileUtils;
import com.club.football.utils.R;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件Controller
 *
 * @author 1
 * @date 2024/01/18
 */
@RestController
@RequestMapping("/files")
@AllArgsConstructor
public class FilesController {

    private final FilesService filesService;

    private final UserService userService;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return {@link R}<{@link String}>
     * @throws IOException IOEXCEPTION
     */
    @PostMapping("/upload")
    public R<String> upload(@RequestPart("file") MultipartFile file) throws IOException {
        return filesService.filesUpload(file);
    }

    /**
     * 上传头像
     *
     * @param file 文件
     * @return {@link R}<{@link String}>
     */
    @PostMapping(value = "/uploadAvatar")
    public R<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            R<String> res = filesService.filesUpload(file);
            Long userId = UserHolder.getUser().getUserId();
            String data = res.getData();
            userService.lambdaUpdate().eq(User::getUserId, userId).set(User::getUserImage, data).update();
            return res;
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 新上载
     *
     * @param file 文件
     * @return {@link R}<{@link String}>
     * @throws IOException IOEXCEPTION
     */
    @PostMapping("/newUpload")
    public R<Map<String, String>> newUpload(@RequestPart("file") MultipartFile file) throws IOException {
        String data = filesService.filesUpload(file).getData();
        String url = FileUtils.getUrl(data);
        HashMap<String, String> map = new HashMap<>(2);
        map.put("url", url);
        return R.ok(map);
    }
}
